#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QDebug>
#include <QSettings>
#include <QCoreApplication>

#include "AutoRun.h"

//----------------------------------------------------------------------------------------
LAutoRun::LAutoRun() {

}


//----------------------------------------------------------------------------------------
void LAutoRun::setApplicationName(QString name) {
    appName = name;
}

//----------------------------------------------------------------------------------------
bool LAutoRun::isInAutoRun() const {
    bool autoRunStat;
    #ifdef Q_WS_X11
        autoRunStat = QFile::exists(QFileInfo(QDir::homePath()+"/.config/autostart/" + appName + ".desktop").absoluteFilePath());
        return autoRunStat;
    #endif

    #ifdef Q_WS_WIN
        QSettings reg("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
        QString pathVal = reg.value(appName).toString();
        QString currentPath = QString("\"%1\"").arg(QDir::toNativeSeparators(QCoreApplication::applicationFilePath()));
        autoRunStat = (pathVal == currentPath);
        return autoRunStat;
    #endif
}

//----------------------------------------------------------------------------------------
void LAutoRun::setAutoRunState(bool param) const {
    if(param) {
#ifdef Q_WS_WIN
        QSettings reg("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
        QString currentPath = QString("\"%1\"").arg(QDir::toNativeSeparators(QCoreApplication::applicationFilePath()));
        reg.setValue(appName, currentPath);
#endif

#ifdef Q_OS_LINUX
        QFile autoRun(QFileInfo(QDir::homePath()+"/.config/autostart/" + appName + ".desktop").absoluteFilePath());
        if (!autoRun.open(QIODevice::WriteOnly))
            return;
        autoRun.write("[Desktop Entry]\n");
        autoRun.write("Type=Application\n");
        autoRun.write(QString("Exec='%1'\n").arg(QCoreApplication::applicationFilePath()).toAscii());
        autoRun.write("Hidden=falsen\n");
        autoRun.write("NoDisplay=false\n");
        autoRun.write("Name=" + appName + "t\n");

        autoRun.close();
#endif
    }
    else {
#ifdef Q_WS_WIN
        QSettings reg("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
        reg.remove(appName);
#endif

#ifdef Q_OS_LINUX
        if (!QFile::remove(QFileInfo(QDir::homePath()+"/.config/autostart/" + appName + ".desktop").absoluteFilePath()))
            return;
#endif
    }
}

//----------------------------------------------------------------------------------------
